<?php

namespace app\shop\controller;

use app\admin\controller\ApiCommon;
use app\shop\model\MaterialTreeModel;
use think\facade\Db;
use think\facade\Filesystem;
use OSS\OssClient;
use OSS\Core\OssUtil;

use OSS\Core\OssException;

class Material extends ApiCommon
{
    /**
     * 上传文件接口
     *
     * @return false
     */
    public function upload()
    {

        /*$request = request()->param();
        $file = request()->file('file');
        $uid = $request['uid'];
        if (empty($file)) {

            return false;

        }
        $saveData = [];
        $type = $file->getOriginalExtension();
        if(in_array($type,['jpg','jpeg','png']))
        {
            $saveData['type'] = 1;
        }elseif(in_array($type,['mp4'])){
            $saveData['type'] = 2;
        }else{
            $saveData['type'] = 0;
        }
        $size = $file->getSize();
        $fileName = $file->getOriginalName();
        $saveName = Filesystem::disk('public')->putFile('image', $file);
        $accessKeyId = "LTAI4FopKKqp8ZE7qMh7x8rL";
        $accessKeySecret = "QU8minZbbZFXsHl9EHq8BmQo3S27lV";
        $endpoint = "oss-cn-zhangjiakou.aliyuncs.com";
        $bucket = "xinyis2017";
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $oss_url = substr($saveName, 6);
        $content = './storage/' . $saveName;// 服务器路径
        $object = "xy_img/" . $oss_url;// OSS路径
        $ossClient->uploadFile($bucket, $object, $content);// 上传
        unlink($content);
        $saveData['save_name'] = $object;
        $saveData['name'] = $fileName;

        $saveData['size'] = $size;


        $saveData['create_time'] = time();

        $saveData['file_path_thumb'] = $thumbSaveName ?? '';

        $saveData['file_path'] = $saveData['save_name'];
        $saveData['uid'] = $uid;
        return resultArray(['data' => $saveData]);*/
        $request = request()->param();

        $file = request()->file('file'); // 获取上传的文件
        $chunk = $request['chunk'];
//        $chunks = $request['chunks'];
        $uid = $request['uid'];
//        $type=pathinfo($request['filename']);

        $fileName = $uid.$chunk; // 拼接分片文件名
        Filesystem::disk('public')->putFileAs( 'topic', $file, $fileName);
        return $this->success([],"成功");

    }
    public function uploadComplete()
    {

        $request = request()->param();
        $chunks = $request['chunks'];
        $uid = $request['uid'];
        $saveData = [];
        $type=pathinfo($request['filename']);
        if(in_array($type['extension'],['jpg','jpeg','png']))
        {
            $saveData['type'] = 1;
        }elseif(in_array($type['extension'],['mp4'])){
            $saveData['type'] = 2;
        }else{
            $saveData['type'] = 0;
        }
        $saveData['name']=$type['filename'];
        $time = time();
        $filePath = './storage/topic/' .$uid . '_' . $time . '.'.$type['extension']; // 拼接最终文件名
        $saveName='topic/'.$uid . '_' . $time . '.'.$type['extension'];
        $fp = fopen($filePath, 'ab'); // 打开最终文件

        for ($i = 0; $i < $chunks; $i++) { // 循环读取分片文件并写入到最终文件

            $partFileName = './storage/topic/'.$uid.$i; // 获取分片文件名
            $partFile=fopen($partFileName,'rb');
            fwrite($fp, fread($partFile, filesize($partFileName))); // 写入到最终文件

            fclose($partFile); // 关闭分片文件

            unlink($partFileName); // 删除分片文件

        }

        fclose($fp); // 关闭最终文件


        $accessKeyId = "LTAI4FopKKqp8ZE7qMh7x8rL";
        $accessKeySecret = "QU8minZbbZFXsHl9EHq8BmQo3S27lV";
        $endpoint = "oss-cn-zhangjiakou-internal.aliyuncs.com";
        $bucket = "xinyiinfors";
        $oss_url = substr($saveName, 6);
        $content = './storage/' . $saveName;// 服务器路径
        $object = "material/" . $oss_url;// OSS路径
        $options = array(
            OssClient::OSS_CHECK_MD5 => true,
            OssClient::OSS_PART_SIZE => 1,
        );
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $content);// 上传
        }catch (\Exception $e)
        {
            return $e->getMessage();
        }

//        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
//
//        $ossClient->multiuploadFile($bucket, $object, $content, $options);
        unlink($content);

        $saveData['create_time']=time();
        $saveData['uid']=$uid;
        $saveData['save_name'] = $object;
        $saveData['file_path'] = $saveData['save_name'];

        return $this->success($saveData, '创建成功');
    }

    public function saveFileLog()
    {
        $request = request()->param();
        $material = new \app\shop\model\Material();
        $insertData = [];
        foreach ($request['saveData'] as $value) {
            $temp['user_id'] = $this->userInfo['id'];
            $temp['url'] = $value['file_path'];
            $temp['tree_id'] = $request['tree_id'];
            $temp['size'] = $value['size'];
            $temp['name'] = $value['name'];
            $temp['type'] = $value['type'];
            array_push($insertData, $temp);
        }
        $material->saveAll($insertData);
        return $this->success([], '创建成功');

    }

    public function getFile()
    {
        $request = request()->param();
        $material = new \app\shop\model\Material();
        $where = [];
        array_push($where, ['tree_id', '=', $request['tree_id']]);
        if(!empty($request['search']['fileName']))
        {
            array_push($where, ['name', 'like', '%'.$request['search']['fileName'].'%']);
        }
        $result = $material->where($where);
        $dataCount = $result->count();
        $data = $result->page($request['page'], $request['limit'])->order('created_at','desc')->column('id,name,url,size,type,created_at');
        foreach ($data as $key => $value) {
            $data[$key]['created_at'] = date('Y-m-d', $value['created_at']);
            $data[$key]['url'] = "http://xinyiinfors.oss-cn-zhangjiakou.aliyuncs.com/" . $value['url'];
            $data[$key]['srcList'][0] = $data[$key]['url'];
            if ($value['size'] > 1024 * 1024 * 1024) {
                $data[$key]['size'] = round($value['size'] / (1024 * 1024 * 1024), 2);
                $data[$key]['size'] = $data[$key]['size'] . "G";
            } else {
                $data[$key]['size'] = round($value['size'] / (1024 * 1024), 2);
                $data[$key]['size'] = $data[$key]['size'] . "M";
            }
        }
        return $this->success($data, '获取成功', $dataCount);
    }

    public function deleteFile()
    {
        $request = request()->param();
        $material = new \app\shop\model\Material();
        $userId = $this->userInfo['id'];
        if (empty($request['id'])) {
            return $this->failed(400, "缺少id");
        }
        $result = $material::find($request['id']);
//        $res = $material::destroy($request['id']);
        if($result->user_id != $userId&&$userId!=867)
        {
            return $this->failed(400, "删除失败");
        }
        $res = $material::destroy($request['id']);
        if (!$res) {
            return $this->failed(400, "删除失败");
        }
        return $this->success([], '删除成功');
    }
    public function downFile()
    {
        $request = request()->param();
        $material = new \app\shop\model\Material();
        $result = $material::find($request['id']);
        if(!$result)
        {
            return $this->failed(400,"下载失败");
        }
        $url="http://xinyiinfors.oss-cn-zhangjiakou.aliyuncs.com/".$result->url;
        header("Content-type: application/octet-stream");
        header('Content-Disposition: attachment; filename="'. basename($url) .'"');
        header("Content-Length: ". $result->size);
        readfile($url);
    }

    public function getTree()
    {
        $tree = new MaterialTreeModel();
        $result = $tree->where('status','=',1)->select()->toArray();
        $data = $this->makeTree($result);
        return resultArray(['data' => [$data]]);
    }

    public function makeTree($list, $children = "children", $key = 0)
    {
        if (empty($list))
            return [];
        $result = [];
        $result[$children] = [];
        $result['label'] = $list[$key]['name'] ?? "/";
        $result['id'] = $list[$key]['id'] ?? "/";
        $id = $list[$key]['id'];
        unset($list[$key]);
        foreach ($list as $k => $value) {
            if ($value['pid'] == $id) {
                $temp = $this->makeTree($list, $children, $k);
                array_push($result[$children], $temp);

            }
        }
        if (empty($result['children'])) {
            unset($result['children']);
            $result['is_leaf'] = 1;
        } else {
            $result['is_leaf'] = 0;
        }
        return $result;
    }

    public function readFile()
    {
        $base_url = "http://xinyis2017.oss-cn-zhangjiakou.aliyuncs.com/";
    }

    public function exportFile()
    {
        $where = [];
        array_push($where, ['member_label', 'like', '%636%']);
//        array_push($where,['create_time','>=',1688140800]);
//        array_push($where,['create_time','<',1690819200]);
        $res1 = Db::name('customer')->where($where)->group('shop_id')->column('count(*)', 'shop_id');
        $where = [];
        array_push($where, ['member_label', 'like', '%637%']);
//        array_push($where,['create_time','>=',1688140800]);
//        array_push($where,['create_time','<',1690819200]);
        $res2 = Db::name('customer')->where($where)->group('shop_id')->column('count(*)', 'shop_id');
        $shop = Db::name('shop')->column('shop_name', 'shop_id');
        $data = [];
        foreach ($res1 as $key => $value) {
            $data[$key]['one'] = $value;
        }
        foreach ($res2 as $key => $value) {
            $data[$key]['two'] = $value;
        }
        foreach ($data as $key => $value) {
            if (empty($data[$key]['one'])) {
                $data[$key]['one'] = 0;
            }
            if (empty($data[$key]['two'])) {
                $data[$key]['two'] = 0;
            }
            $data[$key]['shop_name'] = $shop[$key];
        }

        $callName = ['shop_name' => '店铺', 'one' => '参加780元门票-2023活动', 'two' => '参加主活动2000元以上标签-2023活动'];
        $downUrl = exportExcelData('标签', $callName, $data, 'xlsx', 1);
        return resultArray(['data' => ['url' => 'http://' . $_SERVER['HTTP_HOST'] . $downUrl], 'error' => '获取成功']);

    }
}
